package com.example.mysql.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.IllegalSQLInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import jakarta.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.List;

/**
 * MyBatis-Plus 拦截器
 *
 * @author 龙茶清欢
 * @since 2024-09-24 15:58:43
 */
@Configuration
@MapperScan("com.example.mysql.mapper")
public class MybatisPlusConfig {

    /**
     * 新版分页插件设置，可根据需求选择添加
     * 配置参考 Mybatis-Plus 官网： https://baomidou.com/plugins/
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 插件主体，封装其他场景插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 自动分页插件，以 MYSQL 为数据库
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 添加非法SQL拦截器
        interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
        // 防止全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    @Resource
    private DynamicDataSourceProperties properties;

    // 手动注入多数据源，参考 https://www.kancloud.cn/tracy5546/dynamic-datasource/2319395
    //4.x版本及以上
    @Primary
    @Bean
    public DataSource dataSource(List<DynamicDataSourceProvider> providers) {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(providers);
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        return dataSource;
    }
}

// 关于 Servlet Web 应用程序的关系型数据库相关开发配置参考 Spring 官方文档： https://docs.spring.io/spring-framework/reference/data-access.html
// 关于 Servlet Web 应用程序的非关系型数据库相关开发配置参考 SpringBoot 官方文档： https://docs.spring.io/spring-boot/reference/data/nosql.html


